import { Upload, Icon, Modal } from 'antd'
import {config} from '../../utils'
const {api} = config;

class Avatar extends React.Component {
    state = {
        previewVisible: false,
        previewImage: '',
        fileList: [],
        file:[],
    };

    handleCancel = () => this.setState({ previewVisible: false })

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }

    handleChange = (info) => {
        const { file, fileList } = info;
        const status = file.status;
        if(fileList.length > 0){
            if(status === 'done'){
                if (info.file.response.code == 0) {
                    const img = info.file.response.data.url;
                    this.props.onChange(img);
                } else {
                    message.error(info.file.response.msg)
                    return;
                }
            }
        }else{
            this.props.onChange('');
        }
        
        this.setState({ fileList, file })
    }

    render() {
        const { previewVisible, previewImage, file } = this.state;
        const {title,imgPic} = this.props;
        const fileList = imgPic && file.length == 0 ? [{
            uid: '-1',
            name: 'xxx.png',
            status: 'done',
            url: imgPic
        }] : this.state.fileList;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">{title}</div>
            </div>
        );
        return (
            <div className="clearfix">
                <Upload
                    action={api.uploadArticlePic}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                >
                    {fileList.length > 0 ? null : uploadButton}
                </Upload>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
}
export default Avatar